<template>
    <div class="context">
        <div class="header">
            <div class="logoBox">
                <img class="logo" src="@/assets/img/logo.png" mode="" />
                <span class="logoName">体液智能标本柜</span>
            </div>
        </div>
        <div class="content">
            <div class="contentBox">
                <div class="informationBox">
                    <div class="dateTime">
                        <span class="time">{{ dateTime.time }}</span>
                        <div class="dateWeek">
                            <span>{{ dateTime.date }}</span>
                            <Divider type="vertical" style="width:2px;height:auto;background-color: #888;" />
                            <span>{{ dateTime.week }}</span>
                        </div>
                    </div>
                    <div class="information">
                        <template v-for="(item, index) in data">
                            <div class="list">
                                <span>{{ item.title }}</span>
                                <span>{{ item.num }}</span>
                            </div>
                            <Divider v-if="index !== data.length - 1"
                                style="width:80%;height: 1px; background-color: #888;" />
                        </template>
                    </div>
                </div>
                <div class="introduceVideoBox">
                    <video class="introduceVideo" src="/video/introduce.mp4" preload="metadata" autoplay muted loop
                        :controls="false" />
                </div>
            </div>
        </div>
        <div class="exampleBox">
            <video src="/video/example.mp4" autoplay muted loop :controls="false" preload="metadata" />
        </div>
        <p style="font-size: .2rem;text-align: center;" v-if="device">{{ device.tell }}</p>
    </div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted, h, onUnmounted, computed } from 'vue'
import { Divider, Modal } from 'ant-design-vue'
import { useRouter } from 'vue-router'
import { getTime, isAndroid } from '@/utils/UtilFun'
import { db } from '@/utils/DexieDB'
import { useIntervalFn } from '@vueuse/core'
import { sendDeviceBaseInfoApi, queryServiceNurseApi, queryWhitelistInfoApi, queryServiceInfoApi, addAlarmApi } from '@/API/API'

const router = useRouter()
const weekArr = ['日', '一', '二', '三', '四', '五', '六']
const dateTime = ref({
    date: '',
    time: '',
    week: ''
})
const device = ref<any>({})


const data = reactive([
    {
        title: '已用仓位',
        num: 0
    },
    {
        title: '空余仓位',
        num: 100
    },
])

function getDate() {
    dateTime.value = {
        date: `${new Date().getMonth() + 1}月${new Date().getDate()}日`,
        time: `${new Date().getHours()}:${new Date().getMinutes() < 10 ? '0' + new Date().getMinutes() : new Date().getMinutes()}`,
        week: `星期${weekArr[new Date().getDay()]}`
    }
}

let keySequence = '', timer: any = null
let keypressTimeout: number | null = null

// 监听扫码事件
function EventListener() {
    if (isAndroid()) {
        window.ClosetAndroid.sendLog("Home Vue 添加按键监听");
    }
    document.addEventListener("keyup", handleKeyup);
}
// 处理扫码事件
function handleKeyup(e: KeyboardEvent) {
    // 清除之前的定时器
    if (keypressTimeout) {
        clearTimeout(keypressTimeout);
    }

    if (e.key !== "Enter") {
        keySequence += e.key;
        // console.log('添加按键:', e.key, '当前序列:', keySequence);
        // 设置新的定时器，在一定时间内没有按键则认为输入完成
        keypressTimeout = window.setTimeout(() => {
            console.log('超时自动处理，最终代码:', keySequence);
            handleCode();
        }, 300); // 100ms无新输入则处理
    } else {
        // 按下Enter键时立即处理
        console.log('扫描完成，最终代码:', keySequence);
        handleCode();
    }
}

// 处理扫码结果
async function handleCode() {
    if (!keySequence) {
        clearKeySequence();
        return;
    }

    try {
        // 特殊管理员码处理
        if (keySequence === '999999') {
            router.push({ name: 'Setting', query: { code: keySequence, permission: '管理' } });
            clearKeySequence();
            return;
        }

        // 特殊测试用例码处理
        if (['11111111', '22222222', '33333333', '44444444'].includes(keySequence)) {
            if (device.value.allNum - device.value.used == 0) {
                window.ClosetAndroid.ttsSpeak('当前仓位已满，请联系护士站', 1);
                sendError('舱位剩余空位已满');
                clearKeySequence();
                return;
            }

            router.push({
                name: 'TestTube',
                query: {
                    code: keySequence,
                    name: '张三',
                    sex: '男',
                    groupName: '粪便常规',
                    age: 18
                }
            });
            clearKeySequence();
            return;
        }

        // 先尝试作为患者码处理
        const isPatientHandled = await handleAsPatient();
        if (isPatientHandled) {
            clearKeySequence();
            return;
        }

        // 再尝试作为护士码处理
        const isNurseHandled = await handleAsNurse();
        if (isNurseHandled) {
            clearKeySequence();
            return;
        }



        // 都无法识别的情况
        window.ClosetAndroid.ttsSpeak('未查询到有效信息，请联系护士站或管理员', 1);
        clearKeySequence();
    } catch (error) {
        console.error('处理扫码结果出错:', error);
        window.ClosetAndroid.ttsSpeak('处理过程中发生错误，请重试', 1);
        clearKeySequence();
    }
}

// 处理护士身份验证
async function handleAsNurse(): Promise<boolean> {
    try {
        // 先查本地数据库
        const nurse = await db.nurse.where({ info: keySequence }).first();
        if (nurse) {
            router.push({ name: 'Setting', query: { code: keySequence, permission: nurse.permission } });
            return true;
        }

        // 本地无数据则请求服务器
        const result = await queryServiceNurseApi({
            serial: device.value.serial,
            info: keySequence
        });

        if (result.data) {
            router.push({ name: 'Setting', query: { code: keySequence, permission: result.data.permission } });
            return true;
        }

        return false;
    } catch (error) {
        console.error('护士验证失败:', error);
        return false;
    }
}

// 处理患者信息查询
async function handleAsPatient(): Promise<boolean> {
    try {
        // 检查仓位是否已满
        if (device.value.allNum - device.value.used == 0) {
            window.ClosetAndroid.ttsSpeak('当前仓位已满，请联系护士站', 1);
            sendError('舱位剩余空位已满');
            return false;
        }

        // 先查本地数据库
        const info = await db.info.where({ info: keySequence }).first();
        if (info) {
            router.push({
                name: 'TestTube',
                query: {
                    code: keySequence,
                    name: info.name,
                    sex: info.sex,
                    groupName: info.groupName,
                    age: info.age,
                }
            });
            return true;
        }

        // 本地无数据则请求服务器
        const result = await queryServiceInfoApi({ info: keySequence });
        if (result.data) {
            router.push({
                name: 'TestTube',
                query: {
                    code: keySequence,
                    name: result.data.name,
                    sex: result.data.sex,
                    age: result.data.age,
                    groupName: result.data.groupName,
                    jianchamingcheng: result.data.jianchamingcheng,
                    specimenName: result.data.specimenName,
                }
            });
            return true;
        }

        return false;
    } catch (error) {
        console.error('患者信息查询失败:', error);
        window.ClosetAndroid.ttsSpeak('未查询到有效信息，请联系护士站', 1);
        return false;
    }
}

// 清除扫码序列及相关定时器
function clearKeySequence() {
    keySequence = '';
    if (keypressTimeout) {
        clearTimeout(keypressTimeout);
        keypressTimeout = null;
    }
}

// // 处理扫码结果
// async function handleCode() {
//     if (keySequence) {
//         if (keySequence === '999999') {
//             router.push({ name: 'Setting', query: { code: keySequence, permission: '管理' } })
//         } else if (keySequence === '11111111' || keySequence === '22222222' || keySequence === '33333333' || keySequence === '44444444') {
//             if (device.value.allNum - device.value.used == 0) {
//                 window.ClosetAndroid.ttsSpeak('当前仓位已满，请联系护士站', 1)
//                 sendError('舱位剩余空位已满')
//                 return false
//             }
//             router.push({
//                 name: 'TestTube',
//                 query: {
//                     code: keySequence,
//                     name: '张三',
//                     sex: '男',
//                     groupName: '粪便常规',
//                     age: 18
//                 }
//             })
//         } else {
//             db.nurse.where({ info: keySequence }).first().then((nurse: nurse | undefined) => {
//                 console.log('本地数据库查询nurse', nurse);

//                 if (nurse) {
//                     router.push({ name: 'Setting', query: { code: keySequence, permission: nurse.permission } })
//                     return true
//                 } else {
//                     return false
//                 }
//             }).then(async (res) => {
//                 console.log('查询结果', res);

//                 if (!res) {
//                     console.log('未找到对应的本地护士信息')
//                     return await queryServiceNurse()
//                 } else {
//                     return true
//                 }
//             }).then((res) => {
//                 if (!res) {
//                     if (device.value.allNum - device.value.used == 0) {
//                         window.ClosetAndroid.ttsSpeak('当前仓位已满，请联系护士站', 1)
//                         sendError('舱位剩余空位已满')
//                         return false
//                     }
//                     db.info.where({ info: keySequence }).first().then(info => {
//                         console.log('本地数据库查询info', info);
//                         if (info) {
//                             router.push({
//                                 name: 'TestTube',
//                                 query: {
//                                     code: keySequence,
//                                     name: info.name,
//                                     sex: info.sex,
//                                     groupName: info.groupName,
//                                     age: info.age,
//                                 }
//                             })
//                             return true
//                         } else {
//                             return false
//                         }
//                     }).then(async (res) => {
//                         if (!res) {
//                             console.log('未找到对应的本地试管信息')
//                             return await queryServiceInfo()
//                         }
//                     }).catch(err => {
//                         console.error('试管信息不存在:', err)
//                         window.ClosetAndroid.ttsSpeak('未查询到有效信息，请联系护士站或管理员', 1)
//                     })
//                 } else {
//                     return true
//                 }
//             }).catch(err => {
//                 keySequence = ''
//                 console.error('护士不存在:', err)
//             })
//         }
//     }

//     // 清除定时器
//     if (keypressTimeout) {
//         clearTimeout(keypressTimeout);
//         keypressTimeout = null;
//     }
// }
// // 本地无护士或者患者信息时 询问平台护士患者信息
// async function queryServiceNurse() {
//     console.log('查询平台护士', keySequence);
//     return queryServiceNurseApi({
//         serial: device.value.serial,
//         info: keySequence
//     }).then(async ({ code, data }) => {
//         console.log('查询护士信息成功:', data);
//         if (data) {
//             router.push({ name: 'Setting', query: { code: keySequence, permission: data.permission } })
//             return Promise.resolve(true);
//         } else {
//             return Promise.resolve(false);
//         }
//     }).catch(err => {
//         keySequence = ''
//         return Promise.reject(false);
//     })
// }

// // 本地无试管信息时 询问平台试管信息
// async function queryServiceInfo() {
//     return queryServiceInfoApi({
//         info: keySequence
//     }).then(async ({ code, data }) => {
//         console.log('查询平台info信息成功:', data);
//         if (data) {
//             router.push({
//                 name: 'TestTube',
//                 query: {
//                     code: keySequence,
//                     name: data.name,
//                     sex: data.sex,
//                     age: data.age,
//                     groupName: data.groupName,
//                     jianchamingcheng: data.jianchamingcheng,
//                     specimenName: data.specimenName,
//                 }
//             })
//         } else {
//             keySequence = ''
//             window.ClosetAndroid.ttsSpeak('未查询到有效信息，请联系护士站', 1)
//             return Promise.resolve(false);
//         }
//     }).catch(err => {
//         keySequence = ''
//         window.ClosetAndroid.ttsSpeak('未查询到有效信息，请联系护士站', 1)
//         return Promise.reject(false);
//     })
// }

// 发送报警信息
function sendError(msg: string) {
    addAlarmApi({
        alarmType: msg,
        alarmData: getTime(),
        serial: device.value.serial
    }).then(res => {
        if (res.code === 200) {
            console.log('报警记录发送成功！');
        } else {
            console.log('报警记录发送失败！');
        }
    }).catch(({ error, url, fetchOptions }) => {
        console.error('报警记录发送失败！');
        db.error.add({
            time: getTime(),
            info: msg,
        }).then(() => {
            db.retryTasks.add({
                id: Date.now(),
                time: getTime(),
                url,
                info: fetchOptions
            }).then((id) => {
                console.log('重试任务添加报警记录成功', id);
            }).catch(err => {
                console.log('重试任务添加报警记录失败', err);
            })
        })
    })
}

// 设备初始化
async function deviceInit() {
    device.value = await db.device.get(1) as device;
    const allNum = device.value.allNum
    // const used = 95
    const used = await db.testTube.count()
    device.value.used = used
    data[0].num = used
    data[1].num = allNum - used
}



onMounted(async () => {
    timer = setInterval(() => getDate(), 1000)
    EventListener();
    deviceInit()
})
onUnmounted(() => {
    clearInterval(timer)
    document.removeEventListener("keyup", handleKeyup);
})
</script>
<style lang="scss" scoped>
.context {
    width: 100%;
    height: 100vh;
    background-color: #7593ffff;
    display: flex;
    flex-direction: column;
    overflow: hidden;
}

.header {
    width: 100%;
    height: 1.25rem;
    padding: 0.125rem 0px 0.125rem .25rem;
    position: relative;
    display: flex;
    flex-direction: row;
    justify-content: space-between;

    .logoBox {
        display: flex;
        flex-direction: row;
        align-items: center;

        .logo {
            width: 1.25rem;
            height: 100%;
        }

        .logoName {
            color: #fff;
            font-size: 0.5rem;
            font-family: "textTTF";
            letter-spacing: 4px;
        }
    }

}

.setting {
    width: 2.5rem;
    height: 2.5rem;
    border-radius: 999px;
    background-color: #fff;
    position: absolute;
    right: -1.25rem;
    top: -1.25rem;

    .admin {
        position: absolute;
        top: 58%;
        left: 18%;
        width: 25%;
        height: 25%;
    }
}

.content {
    width: 100%;
    padding: 0.0625rem 0.25rem;
    display: flex;
    box-sizing: border-box;

    .contentBox {
        width: 100%;
        display: flex;
        flex-direction: row;
        justify-content: space-between;

        .informationBox {
            width: 49%;
            height: 7.25rem;
            display: flex;
            flex-direction: column;

            .dateTime {
                width: 100%;
                display: flex;
                align-items: center;
                background: #ffffffB3;
                border-radius: 0.125rem;
                padding: 0.125rem;
                margin-bottom: 0.125rem;
                flex-direction: column;
                box-sizing: border-box;

                .time {
                    font-size: 1.25rem;
                    font-family: '黑体';
                }

                .dateWeek {
                    width: 80%;
                    display: flex;
                    flex-direction: row;
                    justify-content: space-evenly;

                    span {
                        font-size: .375rem;
                    }
                }
            }

            .information {
                width: 100%;
                flex: 1;
                background: #ffffffB3;
                border-radius: 0.125rem;
                display: flex;
                flex-direction: column;
                justify-content: space-evenly;
                align-items: center;
                padding: .25rem;


                .list {
                    width: 100%;
                    display: flex;
                    justify-content: space-around;
                    align-items: center;
                    box-sizing: border-box;

                    span {
                        font-size: .5rem;
                    }

                }

            }
        }
    }


    .introduceVideoBox {
        width: 49%;
        height: 100%;
        border-radius: 0.125rem;
        border: 0.125rem solid #ffffffB3;
        box-sizing: border-box;

        .introduceVideo {
            width: 100%;
            height: 100%;
            object-fit: fill;
        }
    }

}

.exampleBox {
    width: 100%;
    flex: 1;
    padding: 0.125rem .25rem;
    box-sizing: border-box;

    video {
        border: 0.125rem solid #ffffffB3;
        border-radius: 0.125rem;
        box-sizing: border-box;
        width: 100%;
        height: 100%;
        object-fit: fill;
    }
}
</style>